<template>
  <div class="settings-page">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <el-icon><Setting /></el-icon>
              <span style="margin-left: 8px;">系统设置</span>
            </div>
          </template>

          <el-form label-width="150px">
            <el-divider content-position="left">
              <el-icon><Clock /></el-icon>
              <span style="margin-left: 5px;">备份计划</span>
            </el-divider>

            <el-form-item label="自动备份间隔">
              <el-row :gutter="10" style="width: 100%;">
                <el-col :span="12">
                  <el-slider
                    v-model="backupInterval"
                    :min="1"
                    :max="168"
                    :marks="marks"
                    :show-tooltip="false"
                  />
                </el-col>
                <el-col :span="12">
                  <el-input-number
                    v-model="backupInterval"
                    :min="1"
                    :max="168"
                    controls-position="right"
                    style="width: 150px;"
                  />
                  <span style="margin-left: 10px; color: #666;">小时</span>
                </el-col>
              </el-row>
              <div style="margin-top: 10px; color: #999; font-size: 12px;">
                <el-icon><InfoFilled /></el-icon>
                建议设置：测试环境 1-6 小时，生产环境 12-24 小时
              </div>
            </el-form-item>

            <el-form-item label="等效周期">
              <el-tag type="info" size="large">
                {{ getIntervalDescription(backupInterval) }}
              </el-tag>
            </el-form-item>

            <el-form-item label="当前设置">
              <el-tag v-if="currentInterval" type="success" size="large">
                每 {{ currentInterval }} 小时自动备份一次
              </el-tag>
              <el-tag v-else type="info" size="large">加载中...</el-tag>
            </el-form-item>

            <el-form-item>
              <el-button 
                type="primary" 
                @click="saveSettings" 
                :loading="saving"
                size="large"
              >
                <el-icon><Check /></el-icon>
                保存设置
              </el-button>
              <el-button @click="loadSettings" size="large">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>

            <el-divider content-position="left">
              <el-icon><Operation /></el-icon>
              <span style="margin-left: 5px;">手动操作</span>
            </el-divider>

            <el-form-item label="立即备份">
              <el-button 
                type="success" 
                @click="triggerBackupNow"
                :loading="triggering"
                size="large"
              >
                <el-icon><VideoPlay /></el-icon>
                立即执行全部设备备份
              </el-button>
              <div style="margin-top: 10px; color: #999; font-size: 12px;">
                <el-icon><InfoFilled /></el-icon>
                将立即对所有启用自动备份的设备执行备份任务
              </div>
            </el-form-item>

            <el-divider content-position="left">
              <el-icon><FolderOpened /></el-icon>
              <span style="margin-left: 5px;">存储设置</span>
            </el-divider>

            <el-form-item label="备份存储路径">
              <el-input v-model="backupDir" readonly>
                <template #prepend>
                  <el-icon><Folder /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <el-icon><Odometer /></el-icon>
              <span style="margin-left: 8px;">备份统计</span>
            </div>
          </template>

          <div class="stat-item">
            <div class="stat-label">
              <el-icon><Calendar /></el-icon>
              今日备份
            </div>
            <div class="stat-value">{{ stats.today_backups }} 次</div>
          </div>

          <el-divider />

          <div class="stat-item">
            <div class="stat-label">
              <el-icon><Document /></el-icon>
              总备份数
            </div>
            <div class="stat-value">{{ stats.total_backups }} 个</div>
          </div>

          <el-divider />

          <div class="stat-item">
            <div class="stat-label">
              <el-icon><PieChart /></el-icon>
              成功率
            </div>
            <div class="stat-value" style="color: #52c41a;">{{ stats.success_rate }}%</div>
          </div>

          <el-divider />

          <div class="stat-item">
            <div class="stat-label">
              <el-icon><Box /></el-icon>
              存储占用
            </div>
            <div class="stat-value">{{ formatSize(stats.total_backup_size) }}</div>
          </div>
        </el-card>

        <el-card style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <el-icon><QuestionFilled /></el-icon>
              <span style="margin-left: 8px;">使用提示</span>
            </div>
          </template>

          <el-alert 
            title="备份间隔建议" 
            type="info" 
            :closable="false"
            style="margin-bottom: 15px;"
          >
            <ul style="margin: 10px 0; padding-left: 20px; font-size: 13px;">
              <li>核心设备：6-12 小时</li>
              <li>一般设备：24 小时</li>
              <li>边缘设备：48-72 小时</li>
            </ul>
          </el-alert>

          <el-alert 
            title="注意事项" 
            type="warning" 
            :closable="false"
          >
            <ul style="margin: 10px 0; padding-left: 20px; font-size: 13px;">
              <li>间隔时间修改后立即生效</li>
              <li>定期清理旧备份文件</li>
              <li>确保存储空间充足</li>
            </ul>
          </el-alert>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { settingsApi, statsApi, backupApi } from '@/api'
import { ElMessage } from 'element-plus'

const backupInterval = ref(24)
const currentInterval = ref(null)
const backupDir = ref('./backups')
const saving = ref(false)
const triggering = ref(false)
const stats = ref({
  today_backups: 0,
  total_backups: 0,
  success_rate: 0,
  total_backup_size: 0
})

// 滑块标记点
const marks = {
  1: '1h',
  6: '6h',
  12: '12h',
  24: '1天',
  48: '2天',
  72: '3天',
  168: '7天'
}

const loadSettings = async () => {
  try {
    const data = await settingsApi.getSettings()
    backupInterval.value = data.backup_interval_hours
    currentInterval.value = data.backup_interval_hours
    backupDir.value = data.backup_dir
  } catch (error) {
    ElMessage.error('加载设置失败')
  }
}

const loadStats = async () => {
  try {
    stats.value = await statsApi.getStatistics()
  } catch (error) {
    console.error('加载统计失败')
  }
}

const saveSettings = async () => {
  if (backupInterval.value === currentInterval.value) {
    ElMessage.info('设置未改变')
    return
  }

  saving.value = true
  try {
    await settingsApi.updateBackupInterval(backupInterval.value)
    currentInterval.value = backupInterval.value
    ElMessage.success({
      message: `备份间隔已更新为 ${backupInterval.value} 小时`,
      duration: 3000
    })
  } catch (error) {
    ElMessage.error(error.response?.data?.detail || '保存失败')
  } finally {
    saving.value = false
  }
}

const triggerBackupNow = async () => {
  triggering.value = true
  try {
    const result = await backupApi.triggerAllBackup()
    ElMessage.success({
      message: result.message,
      duration: 3000
    })
    // 3秒后刷新统计
    setTimeout(loadStats, 3000)
  } catch (error) {
    ElMessage.error('触发备份失败')
  } finally {
    triggering.value = false
  }
}

const getIntervalDescription = (hours) => {
  if (hours < 6) return `每 ${hours} 小时（高频备份）`
  if (hours === 6) return '每 6 小时（每天4次）'
  if (hours === 12) return '每 12 小时（每天2次）'
  if (hours === 24) return '每 24 小时（每天1次）'
  if (hours === 48) return '每 48 小时（每2天1次）'
  if (hours === 72) return '每 72 小时（每3天1次）'
  if (hours === 168) return '每 168 小时（每周1次）'
  
  const days = Math.floor(hours / 24)
  const remainHours = hours % 24
  if (days > 0 && remainHours === 0) return `每 ${days} 天`
  if (days > 0) return `每 ${days} 天 ${remainHours} 小时`
  return `每 ${hours} 小时`
}

const formatSize = (bytes) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB'
  if (bytes < 1024 * 1024 * 1024) return (bytes / 1024 / 1024).toFixed(2) + ' MB'
  return (bytes / 1024 / 1024 / 1024).toFixed(2) + ' GB'
}

onMounted(() => {
  loadSettings()
  loadStats()
})
</script>

<style scoped>
.settings-page {
  max-width: 1400px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 500;
  font-size: 16px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.stat-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #1890ff;
}

.info-card :deep(.el-divider) {
  margin: 12px 0;
}
</style>

